﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using FireStarterModeller.BO;
using Habanero.Base;
using Habanero.BO;

namespace FireStarterModeller.Logic
{
    public class XmlPersistor : IBoPersistor
    {
        private List<BusinessObject> _businessObjects = new List<BusinessObject>(5);
        private TextWriter _textWriter;

        public XmlPersistor(TextWriter textWriter)
        {
            _textWriter = textWriter;
        }

        public void Persist()
        {
            XmlWriter xmlWriter = CreateXmlWriter();
            xmlWriter.WriteStartElement("BusinessObjects");
            foreach (BusinessObject businessObject in _businessObjects)
            {
                WriteBusinessObject(xmlWriter, businessObject);
            }
            xmlWriter.WriteEndElement();
            xmlWriter.Close();
        }

        private XmlWriter CreateXmlWriter()
        {
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.OmitXmlDeclaration = true;
            xmlWriterSettings.Indent = true;
            return XmlWriter.Create(_textWriter, xmlWriterSettings);
        }

        private void WriteBusinessObject(XmlWriter xmlWriter, BusinessObject businessObject)
        {
            xmlWriter.WriteStartElement(XmlConvert.EncodeLocalName(businessObject.ClassDef.ClassName));
            foreach (BOProp boProp in businessObject.Props)
            {
                object value = boProp.Value;
                
                xmlWriter.WriteStartAttribute(boProp.PropertyName);
                if (value != null)
                {
                    if (value is DateTime)
                    {
                        xmlWriter.WriteValue(value);
                    } else
                    {
                        xmlWriter.WriteString(boProp.PropertyValueString);
                    }
                }
                xmlWriter.WriteEndAttribute();
            }
            xmlWriter.WriteEndElement();
        }

        public void AddBusinessObject(BusinessObject businessObject)
        {
            if (_businessObjects.Contains(businessObject)) return;
            _businessObjects.Add(businessObject);
        }

        public List<BusinessObject> BusinessObjects
        {
            get { return _businessObjects; }
        }
    }
}
